package com.bbx.taxi.client.DB;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.bbx.api.sdk.model.comm.returns.line.To_Cities;
import com.bbx.taxi.client.MyApplication;
import com.bbx.taxi.client.Bean.Value;
import com.bbx.taxi.client.DB.Util.DBHelper;
import com.bbx.taxi.client.DB.Util.DBcolumns;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class AddressDB implements DBcolumns {
	private DBHelper helper;
	public int count_collect = 5;// 收藏格式

	public AddressDB() {
		MyApplication myApplication=MyApplication.getInstance();
		helper = DBHelper.getInstance(myApplication.getApplicationContext(), null);
	}

	/**
	 * 打开只读的数据库
	 */
	public SQLiteDatabase onOpenRead() {
		if(helper==null){
			helper = DBHelper.getInstance(MyApplication.getInstance().getApplicationContext(), null);
		}
		SQLiteDatabase SQLdb ;
		try{SQLdb= helper.getReadableDatabase();}catch(Exception e){
			helper = DBHelper.getInstance(MyApplication.getInstance().getApplicationContext(), null);
			SQLdb= helper.getReadableDatabase();
		}
		return SQLdb;
	}

	/**
	 * 打开只写的数据库
	 */
	public SQLiteDatabase onOpenWrite() {
		if(helper==null){
			helper = DBHelper.getInstance(MyApplication.getInstance().getApplicationContext(), null);
		}
		SQLiteDatabase SQLdb ;
		try{SQLdb= helper.getReadableDatabase();}catch(Exception e){
			helper = DBHelper.getInstance(MyApplication.getInstance().getApplicationContext(), null);
			SQLdb= helper.getReadableDatabase();
		}
		return SQLdb;
	}

	/**
	 * 查询
	 */
	public Cursor onQuery() {
		SQLiteDatabase SQLdb = onOpenRead();
		Cursor cursor = SQLdb.query(TABLE_ADDRESS, null, null, null, null,
				null, ADDRESS_ID + " desc");
		return cursor;

	}

	/**
	 * 查询收藏或者历史
	 */
	public Cursor onQuery(String isCollection) {// 1为收藏，0为历史
		SQLiteDatabase SQLdb = onOpenRead();
		String[] args = { isCollection };
		Cursor cursor = SQLdb.query(TABLE_ADDRESS, null, ADDRESS_COLLECTION
				+ "=?", args, null, null, ADDRESS_ID + " desc");
		return cursor;

	}

	/**
	 * 查询最后一条记录,记得关掉数据库
	 */
	public Cursor onQueryLast() {
		SQLiteDatabase SQLdb = onOpenRead();
		String sql = "select * from " + TABLE_ADDRESS + " order by "
				+ ADDRESS_ID + " desc limit 1";
		String[] args = new String[] {};
		Cursor cursor = SQLdb.rawQuery(sql, args);
		return cursor;

	}

	/**
	 * 删除
	 */
	public void onDelete() {
		SQLiteDatabase SQLdb = onOpenWrite();
		SQLdb.delete(TABLE_ADDRESS, null, null);
		SQLdb.close();
	}

	/**
	 * 根据Id删除
	 */
	public void onDelete(String rowId) {
		SQLiteDatabase SQLdb = onOpenWrite();
		String[] whereArgs = { String.valueOf(rowId) };
		int i = SQLdb.delete(TABLE_ADDRESS, ADDRESS_ID + "=?", whereArgs);
		SQLdb.close();
	}

	/**
	 * 根据经纬度删除
	 */
	public void onDelete(double longitude, double latitude) {

		SQLiteDatabase SQLdb = onOpenWrite();
		String[] whereArgs = { String.valueOf(longitude),
				String.valueOf(latitude) };
		int i = SQLdb.delete(TABLE_ADDRESS, ADDRESS_LONGITUDE + "=? and "
				+ ADDRESS_LATITUDE + " =?", whereArgs);
		SQLdb.close();
	}
	/**
	 * 根据经纬度删除
	 */
	public void onDelete(String name, String  address) {

		SQLiteDatabase SQLdb = onOpenWrite();
		String[] whereArgs = {name,address };
		int i = SQLdb.delete(TABLE_ADDRESS, ADDRESS_NAME + "=? and "
				+ ADDRESS_ADDRESS + " =?", whereArgs);
		SQLdb.close();
	}
	/**
	 * 更新一条数据
	 */
	public void onUpdate(String rowId, String name, String city,
			String address, String lnt, String lat, String collection) {
		SQLiteDatabase SQLdb = onOpenWrite();
		ContentValues cv = new ContentValues();
		cv.put(ADDRESS_NAME, name);
		cv.put(ADDRESS_CITY, city);
		cv.put(ADDRESS_ADDRESS, address);
		cv.put(ADDRESS_LONGITUDE, lnt);
		cv.put(ADDRESS_LATITUDE, lat);
		cv.put(ADDRESS_COLLECTION, collection);
		SQLdb.update(TABLE_ADDRESS, cv, ADDRESS_ID + "=" + rowId, null);
		SQLdb.close();
	}

	/**
	 * 更新一条数据,只更新收藏
	 */
	public void onUpdate(String rowId, String collection) {
		SQLiteDatabase SQLdb = onOpenWrite();
		ContentValues cv = new ContentValues();
		cv.put(ADDRESS_COLLECTION, collection);
		SQLdb.update(TABLE_ADDRESS, cv, ADDRESS_ID + "=" + rowId, null);
		SQLdb.close();
	}

	/**
	 * 插入一条数据 ,collection为1则代表收藏，0为历史
	 */
	public void onWrite(String name, String city, String address,
			double longitude, double latitude, String collection) {
		//查询该地址的收藏是否存在
		collection=readAllDB(Value.ADDRESS_TYPE_COLLECTE,longitude,latitude)?Value.ADDRESS_TYPE_COLLECTE:Value.ADDRESS_TYPE_HISTORY;
//		// 写入之前，先清空同一个经纬度
//		onDelete(longitude, latitude);
		//写入之前，先清空名字跟地址一样
		onDelete(name,address);
		SQLiteDatabase SQLdb = onOpenWrite();
		ContentValues values = new ContentValues();
		values.put(ADDRESS_NAME, name);
		values.put(ADDRESS_CITY, city);
		values.put(ADDRESS_ADDRESS, address);
		values.put(ADDRESS_LONGITUDE, String.valueOf(longitude));
		values.put(ADDRESS_LATITUDE, String.valueOf(latitude));
		values.put(ADDRESS_COLLECTION, collection);
		SQLdb.insert(TABLE_ADDRESS, ADDRESS_ID, values);
		SQLdb.close();
	}

	/**
	 * 根据类型读取对应的城市 所有数据
	 */
	public List<Map<String, String>> readAllDB(Context context, String type,
			String cityname) {
		List<Map<String, String>> list = new ArrayList<Map<String, String>>();
		Cursor c = onQuery(type);
		c.moveToFirst();
		if (c.getCount() > 0) {
			do {
				Map<String, String> map = new HashMap<String, String>();
				for (int i = 0; i < c.getColumnCount(); i++) {
					map.put(c.getColumnName(i), c.getString(i));
				}
					String city = "";
					// 城市为空
					if (map.get(DBcolumns.ADDRESS_CITY) == null
							|| map.get(DBcolumns.ADDRESS_CITY).equals("")) {
						String address_name = map.get(DBcolumns.ADDRESS_NAME);
						if (address_name.contains(" ")) {
							city = address_name.substring(0,
									address_name.indexOf(" "));
						} else if (address_name.contains("\t")) {
							city = address_name.substring(0,
									address_name.indexOf("\t"));
						} else if (address_name.contains("-")) {
							city = address_name.substring(0,
									address_name.indexOf("-"));
						}
					} else {
						city = map.get(DBcolumns.ADDRESS_CITY);
					}
					if (city.startsWith(cityname)) {
					   list.add(map);
					}
			} while (c.moveToNext());
		}
		c.close();
		onColse();
		//寻找有空的地址，如果空的地址有2个，则取一个
		List<Map<String, String>> list1 = new ArrayList<Map<String, String>>();
		List<Map<String, String>> list2 = new ArrayList<Map<String, String>>();
		list1.addAll(list);
		list2.addAll(list);
       for(int i=list1.size()-1;i>=0;i--){
    	   String name=list1.get(i).get(DBcolumns.ADDRESS_NAME);
    	   String address=list1.get(i).get(DBcolumns.ADDRESS_ADDRESS);
    	   if(address.equals("")){
    		  for(int j=list2.size()-1;j>=0;j--){
    			  String name2=list2.get(j).get(DBcolumns.ADDRESS_NAME);
    			  String address2=list2.get(j).get(DBcolumns.ADDRESS_ADDRESS);
    			  if(name.equals(name2)&&!address2.equals("")){
    				  list1.remove(i);
    			  }
    		  }
    	   }
       }
		return list1;
	}
	/**
	 * 根据类型读取 所有数据
	 */
	public List<Map<String, String>> readAllDB(Context context, String type) {
		List<Map<String, String>> list = new ArrayList<Map<String, String>>();
		Cursor c = onQuery(type);
		c.moveToFirst();
		if (c.getCount() > 0) {
			do {
				Map<String, String> map = new HashMap<String, String>();
				for (int i = 0; i < c.getColumnCount(); i++) {
					map.put(c.getColumnName(i), c.getString(i));
				}
				list.add(map);
			} while (c.moveToNext());
		}
		c.close();
		onColse();

		return list;
	}
	/**
	 * 根据收藏经纬度查询是否含有该数据
	 */
	public boolean readAllDB(String isCollection,double longitude, double latitude) {
		boolean isExist=false;
		SQLiteDatabase SQLdb = onOpenRead();
		String[] whereArgs = { isCollection,String.valueOf(longitude),
				String.valueOf(latitude) };
		Cursor c = SQLdb.query(TABLE_ADDRESS, null,ADDRESS_COLLECTION+"=? and " +ADDRESS_LONGITUDE + "=? and "
				+ ADDRESS_LATITUDE + " =?", whereArgs, null, null, ADDRESS_ID + " desc");
		c.moveToFirst();
		if (c.getCount() > 0) {
			isExist=true;
		}
		else{
			isExist=false;
		}
		c.close();
		onColse();

		return isExist;
	}
	/**
	 * 刷新最新数据
	 */
	public Map<String, String> readADB() {
		Map<String, String> map = new HashMap<String, String>();
		Cursor c = onQueryLast();
		c.moveToNext();
		if (c.getCount() > 0) {
			for (int i = 0; i < c.getColumnCount(); i++) {
				map.put(c.getColumnName(i), c.getString(i));
			}
		}
		c.close();
		return map;
	}

	/**
	 * 关闭数据库
	 */
	public void onColse() {
		SQLiteDatabase SQLdb = onOpenWrite();
		SQLdb.close();
	}

	/**
	 * 判断收藏个数是否已满
	 */
	public boolean isCollectCountFull(Context context) {
		if (readAllDB(context, Value.ADDRESS_TYPE_COLLECTE).size() >= count_collect) {
			return true;
		} else
			return false;
	}
}
